home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: Utrecht.NL.net!news
- From: Franz Korntner <fkorntne@bazis.nl>
- Subject: Re: random number
- X-Nntp-Posting-Host: bastion1.bazis.nl
- Content-Type: text/plain; charset=us-ascii
- Message-ID: <3115D5B3.41C6@bazis.nl>
- Sender: news@inter.NL.net (News at newsutr)
- Content-Transfer-Encoding: 7bit
- Organization: NLnet
- Mime-Version: 1.0
- Date: Mon, 5 Feb 1996 10:02:27 GMT
- X-Mailer: Mozilla 2.0b6a (X11; I; OSF1 V3.2 alpha)
-
- > >Hi,
- > >Could anybody help me to generate some code to produce
- > >a random number between -3 and 3 ?
- > >I'm trying to use rand(), but since it doesn't receive
- >
- > Each time you call rand map the result into the interval -3 ... 3.
- > You can do this, for example, as follows:
- >
- > r = (rand() % 7) - 3;
- >
- > If you are using rand be sure and read about the role of srand
- > in "initializing" the sequence of random numbers that are generated.
-
- You are using rand()%7 to get a number in the range 0..7 but this method is
- incorrect. Performing operations on random numbers is okay as long as all
- bits of the number are included in the operation. It is known to be
- dangerous to extract bits from a pseudo-random number and assume that those
- bits have random properties. Even worse, it is also known that the less
- significant bits of some random number generators are not random at all! In
- this case you are selecting the 3 most less significant bits of the number,
- the worst choice that could have been made. A better solution is to use the
- magnitude of the random number, but such operations are implemention
- dependent (overflows, and such) as in:
- (rand()*7)/(MAXRAND+1)
-
- --
- +-----------------------------------------------------------------------+
- | Franz Korntner at BAZIS, dept. System Development, Leiden, Netherlands|
- | E-mail: fkorntne@bazis.nl |
- +-----------------------------------------------------------------------+
-